#pragma once

#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>

#include "init.hpp"
#include "log.hpp"

dict d;

class Task
{
public:
    Task(int sockfd, uint16_t port, std::string &ip)
        : sockfd_(sockfd), _port(port), ip_(ip)
    {
    }

    void operator()()
    {
        run();
    }

    void run()
    {
        while (true)
        {
            char buffer[4096];

            ssize_t n = read(sockfd_, &buffer, sizeof(buffer));
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "client key# " << buffer << std::endl;
                // 翻译功能
                std::string echo_str = d.translations(buffer);
                // std::cout << echo_str <<std::endl;

                // 写回客户端
                n = write(sockfd_, echo_str.c_str(), sizeof(echo_str));
                if (n < 0)
                {
                    lg(WARNING, "write client error, errno: %d,error", errno, strerror(errno));
                }
            }
            else if (n == 0)
            {
                lg(INFO, "%s:%d quit, server close sockfd: %d", ip_.c_str(), _port, sockfd_);
                break;
            }
            else
            {
                lg(INFO, "read error,sockfd: %d,port: %d,ip: %s", sockfd_, _port, ip_.c_str());
                break;
            }
        }

        // 关闭文件
        close(sockfd_);
    }

private:
    int sockfd_;
    uint16_t _port;
    std::string ip_;
};